import sys
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QLabel, QPushButton, QLineEdit, QScrollArea, QRadioButton, \
    QPlainTextEdit, QVBoxLayout, QHBoxLayout, QFileDialog, QApplication, QComboBox
from PySide2.QtGui import QIcon, QImage, QPixmap

import baidu_api_config as bac
import CQLabel

import utl_text

class MyWidget(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("Py-BaiduOCR")
        self.setWindowIcon(QIcon("./resources/Py-BaiduOCR.svg"))

        # 数据
        self.imageInfo = ""
        self.imagePath = ""
        self.scaleFactor = 1
        ## 字句方向（Text Line Direction）
        self.descTLD = ["字向：左右，句向：上下",
                        "字向：右左，句向：上下",
                        "字向：上下，句向：左右",
                        "字向：上下，句向：右左"]
        self.dataTLD = ["ltrttb",
                        "rtlttb",
                        "ttbltr",
                        "ttbrtl"]
        self.text = []

        # 输入
        self.labelIn = QLabel("输入：")
        self.btnSelectImage = QPushButton("选择图片")
        self.btnSelectImage.setIcon(QIcon("./resources/image.svg"))
        self.btnZoomOut = QPushButton("缩小图片")
        self.btnZoomOut.setIcon(QIcon("./resources/zoomout.svg"))
        self.btnZoomIn = QPushButton("放大图片")
        self.btnZoomIn.setIcon(QIcon("./resources/zoomin.svg"))
        self.btnZoomOut.setMinimumWidth(50)
        self.btnZoomIn.setMinimumWidth(50)
        self.lineditImagePath = QLineEdit()
        self.labelImage = CQLabel.CLabel()
        self.scrollArea = QScrollArea()

        # 输出
        self.labelOut = QLabel("输出：")
        self.cbbTextDirect = QComboBox()
        self.cbbTextDirect.addItems( self.descTLD)
        for i in range(len(self.descTLD)):
            self.cbbTextDirect.setItemData(i, self.dataTLD[i], Qt.UserRole)
        self.btnCrop = QRadioButton("限定选区")
        self.btnCrop.setIcon(QIcon("./resources/rect.svg"))
        self.btnOCR = QPushButton("识别文字")
        self.btnOCR.setIcon(QIcon("./resources/ocr.svg"))
        self.btnCopy = QPushButton("复制")
        self.btnCopy.setIcon(QIcon("./resources/copy.svg"))
        self.btnClear = QPushButton("清空")
        self.btnClear.setIcon(QIcon("./resources/clear.svg"))
        self.btnCut = QPushButton("剪切")
        self.btnCut.setIcon(QIcon("./resources/cut.svg"))
        self.pteResult = QPlainTextEdit()

        # 排版
        self.layout1 = QVBoxLayout()
        self.layout1.addWidget(self.labelIn)

        self.layout2 = QHBoxLayout()
        self.layout2.addWidget(self.btnSelectImage)
        self.layout2.addWidget(self.lineditImagePath)
        self.layout2.addWidget(self.btnZoomOut)
        self.layout2.addWidget(self.btnZoomIn)

        self.layout1.addLayout(self.layout2)

        self.layout1.addWidget(self.scrollArea)
        self.layout1.addWidget(self.labelOut)

        layout3 = QHBoxLayout()
        layout3.addWidget(self.cbbTextDirect)
        layout3.addWidget(self.btnCrop)
        layout3.addWidget(self.btnOCR)
        layout3.addWidget(self.btnCopy)
        layout3.addWidget(self.btnClear)
        layout3.addWidget(self.btnCut)

        self.layout1.addLayout(layout3)
        self.layout1.addWidget(self.pteResult)

        self.setLayout(self.layout1)

        # 动作绑定
        self.btnSelectImage.clicked.connect(self.selectImage)
        self.btnZoomIn.clicked.connect(self.zoomIn)
        self.btnZoomOut.clicked.connect(self.zoomOut)
        self.btnOCR.clicked.connect(self.ocr)
        self.btnCopy.clicked.connect(self.copyText)
        self.btnClear.clicked.connect(self.clearText)
        self.btnCut.clicked.connect(self.cutText)

    """ 选择图片 """
    def selectImage(self):
        dialog = QFileDialog(self)
        dialog.setFileMode(QFileDialog.ExistingFile)
        self.imageInfo = dialog.getOpenFileName()
        self.imagePath = self.imageInfo[0]
        self.lineditImagePath.setText(self.imagePath)
        self.showImage()

    """ 展示图片 """
    def showImage(self):
        # 使用QImage存储图片
        image = QImage(self.imagePath)
        self.labelImage.setPixmap(QPixmap.fromImage(image))
        self.labelImage.setScaledContents(True)
        self.scrollArea.setWidget(self.labelImage)

    """ 缩放图片 """
    def scaleImage(self, factor):
        self.scaleFactor *= factor
        self.labelImage.resize(self.scaleFactor * self.labelImage.pixmap().size())

    """ 缩小图片 """
    def zoomOut(self):
        self.scaleImage(0.8)

    """ 放大图片 """
    def zoomIn(self):
        self.scaleImage(1.25)

    """ 读取文件内容 """
    def get_file_content(self, path):
        with open(path, 'rb') as fp:
                return fp.read()

    """ 识别文字 """
    def ocr(self):
        if self.btnCrop.isChecked():
            self.imagePath = "./resources/temp_CLabel.jpg"
        else:
            self.imagePath = self.imageInfo[0]
        image = self.get_file_content(self.imagePath)
        # 调用通用文字识别, 图片参数为本地图片
        ret = bac.client.basicAccurate(image)
        # 清空文本变量
        self.text.clear()
        for each in ret['words_result']:
            self.text.append(each['words'])
        if self.cbbTextDirect.currentData() == 'ltrttb':
            self.pteResult.appendPlainText(utl_text.get_ltrttb(self.text))
        elif self.cbbTextDirect.currentData() == 'rtlttb':
            self.pteResult.appendPlainText(utl_text.get_rtlttb(self.text))
        elif self.cbbTextDirect.currentData() == 'ttbltr':
            self.pteResult.appendPlainText(utl_text.get_ttbltr(self.text))
        elif self.cbbTextDirect.currentData() == 'ttbrtl':
            self.pteResult.appendPlainText(utl_text.get_ttbrtl(self.text))

    """ 复制 """
    def copyText(self):
        self.pteResult.selectAll()
        self.pteResult.copy()

    """ 清空 """
    def clearText(self):
        self.pteResult.selectAll()
        self.pteResult.clear()

    """ 剪切 """
    def cutText(self):
        self.pteResult.selectAll()
        self.pteResult.cut()


if __name__ == "__main__":
    app = QApplication([])

    widget = MyWidget()
    widget.resize(1024, 800)
    widget.show()

    sys.exit(app.exec_())